import React, { useState, useEffect } from 'react';
import OpenApi from '../../utils/api.jsx'; // 导入API函数
import "./usertable.css";
import ModifyUserMessage from './modifyUserMessage';

function UserTable() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    try {
      const response = await OpenApi.fetchUsers();
      console.log(response.data.users);
      var result = [];
      for (var i = 1; i <= response.data.users.length - 1; i++) {
        result[i - 1] = response.data.users[i];
      }
      console.log(result);
      setUsers(result);
    } catch (error) {
      console.error('Error fetching users:', error);
    }
  };

  const handleDelete = async (userID) => {
    try {
      await OpenApi.deleteUser(userID);
      fetchUsers(); // 删除成功后重新获取用户列表
    } catch (error) {
      console.error('Error deleting user:', error);//获取错误信息并打印到控制台
    }
  };

  return (
    <div>
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>手机号</th>
            <th>身份</th>
            <th>角色ID</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {users.map((user) => (
            <tr key={user.userId}>
              <td>{user.userId}</td>
              <td>{user.userName}</td>
              <td>{user.phone}</td>
              <td>{user.identify}</td>
              <td>{user.roleID}</td>
              <td>
                <span style={{ display: 'inline-block', marginRight: '10px' }}>
                  <button style={{ width: 70, height: 40 }} onClick={() => handleDelete(user.userId)}>删除</button>
                </span>
                <span style={{ display: 'inline-block', marginRight: '10px' }}>
                  <ModifyUserMessage user={user} userID={user.userId} />
                </span>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default UserTable;
